package com.zl.ble.connect;

import android.bluetooth.BluetoothSocket;
import android.util.Log;

import com.zl.ble.BLEConstants;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;
    private ConnectedListener mConnectedListener;

    public ConnectedThread(BluetoothSocket socket) {
        this.mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) {
            Log.e(BLEConstants.TAG, "temp sockets not created", e);
        }
        mmInStream = tmpIn;
        mmOutStream = tmpOut;
        if (mConnectedListener != null) {
            mConnectedListener.onConnected();
        }
    }

    public void setConnectedListener(ConnectedListener mConnectedListener) {
        this.mConnectedListener = mConnectedListener;
    }

    public void run() {
        Log.i(BLEConstants.TAG, "BEGIN mConnectedThread");
        byte[] bytes = new byte[4096];
        while (true) {
            try {
                while ((mmInStream.read(bytes)) != -1) {
                    if (mConnectedListener != null) {
                        mConnectedListener.onReceive(bytes);
                    }
                }
            } catch (IOException e) {
                Log.e(BLEConstants.TAG, "disconnected", e);
                if (mConnectedListener != null) {
                    mConnectedListener.onDisConnected(e);
                }
                break;
            }
        }
    }

    public boolean write(byte[] buffer) {
        try {
            mmOutStream.write(buffer);
            return true;
        } catch (IOException e) {
            Log.e(BLEConstants.TAG, "Exception during write", e);
            return false;
        }
    }


    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) {
            Log.e(BLEConstants.TAG, "close() of connect socket failed", e);
        }
    }
}
